package com.biz.primus.ms.commodity.dao.redis;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.commodity.vo.evaluation.frontend.EvaluationRequestDTO;
import com.biz.primus.ms.commodity.dao.ro.EvaluationRo;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

/**
 * @author yangzichun
 * @date 2017/2/9
 */
@Repository
public class EvaluationRedisDao extends CrudRedisDao<EvaluationRo, Long> implements Serializable {
	private static final long serialVersionUID = -5950832172677027189L;

	/**
	 * 根据店铺 id 分页查询全部评论
	 * 
	 * @param reqVo
	 *            店铺 id 分页查询对象 vo
	 * @return 评价 ro 集合
	 */
	public List<EvaluationRo> findByVendorId(EvaluationRequestDTO reqVo) {
		if (reqVo != null && reqVo.getVendorId() != null) {
			Set<byte[]> idBytes = super.zrevrange(getFieldSortedSetKey("vendorId", reqVo.getVendorId()),
					Math.max(0, reqVo.getPage() - 1) * reqVo.getLimit(),
					Math.max(1, reqVo.getPage()) * reqVo.getLimit() - 1);

			if (CollectionUtils.isNotEmpty(idBytes)) {
				return findByIds(idBytes);
			}
		}
		return Lists.newArrayList();
	}

	public List<EvaluationRo> findByEvaluationProductCode(EvaluationRequestDTO requestDTO) {
		if (requestDTO != null && requestDTO.getProductCode() != null) {
			Set<byte[]> idBytes = super.zrevrange(getFieldSortedSetKey("productCode", requestDTO.getProductCode()),
					Math.max(0, requestDTO.getPage() - 1) * requestDTO.getLimit(),
					Math.max(1, requestDTO.getPage()) * requestDTO.getLimit() - 1);

			if (CollectionUtils.isNotEmpty(idBytes)) {
				return findByIds(idBytes);
			}
		}
		return Lists.newArrayList();
	}

	public List<EvaluationRo> findAllByVendorId(Long vendorId) {
		if (vendorId != null) {
			Set<byte[]> idBytes = super.zrevrange(getFieldSortedSetKey("vendorId", vendorId), 0, -1);
			if (CollectionUtils.isNotEmpty(idBytes)) {
				return findByIds(idBytes);
			}
		}
		return Lists.newArrayList();
	}

	/**
	 * 根据商品编码计算商品评论总数
	 * 
	 * @param productCode
	 * @return
	 */
	public Long countByProductCodeTotal(String productCode) {
		Long count = 0L;
		if (!StringUtils.isBlank(productCode)) {
			count = super.zCard(getFieldSortedSetKey("productCode", productCode));
		}
		return count;
	}

	/**
	 * 根据店铺ID计算店铺评论总数
	 * 
	 * @param productCode
	 * @return
	 */
	public Long countByVendorIdTotal(String vendorId) {
		Long count = 0L;
		if (!StringUtils.isBlank(vendorId)) {
			count = super.zCard(getFieldSortedSetKey("vendorId", vendorId));
		}
		return count;
	}

}
